﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Web.Script.Serialization;

namespace KMFrame.Util
{
    public class JsonHelper
    {
        public static string GetJson(IEnumerable<object> list,string keyname)
        {
            StringBuilder jsonBuilder = new StringBuilder();

            jsonBuilder.Append("{\"page\":1,\"total\":" + list.Count().ToString() + ",\"records\":" + list.Count().ToString() + ",\"rows\"");
            jsonBuilder.Append(":[");
            int i = 0;
            foreach (object o in list)
            {
                PropertyInfo key = o.GetType().GetProperty(keyname);
                object kv = key.GetValue(o, null);
                string ks = (kv == null) ? "" : kv.ToString();
                jsonBuilder.Append("{\"id\":" + ks + ",\"cell\":[");
                
                foreach (PropertyInfo f in o.GetType().GetProperties())
                {
                    jsonBuilder.Append("\"");
                    object ro = f.GetValue(o, null);
                    string rs = (ro == null) ? "" : ro.ToString();
                    jsonBuilder.Append(rs);
                    jsonBuilder.Append("\",");
                }
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                jsonBuilder.Append("]},");
                i++;
            }
            jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            jsonBuilder.Append("]");
            jsonBuilder.Append("}");
            return jsonBuilder.ToString();
        }

        /// <summary>
        /// 对象转JSON
        /// </summary>
        /// <param name="obj">对象</param>
        /// <returns>JSON格式的字符串</returns>
        public static string ObjectToJSON(object obj)
        {
            JavaScriptSerializer jss = new JavaScriptSerializer();
            try
            {
                return jss.Serialize(obj);
            }
            catch (Exception ex)
            {

                throw new Exception("JSONHelper.ObjectToJSON(): " + ex.Message);
            }
        }
    }
}
